﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using vngoodlife.Singleton;
using vngoodlife.Util;

namespace vngoodlife.Controllers
{
    public class TagsController : Controller
    {

        #region BackEnd
        
        
        /// <summary>
        /// use in page ArticleEdit to autocomplete in field tags. Ajax
        /// </summary>
        /// <param name="term"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult GetTags(string term)
        {
            term = term.Trim();
            var artTagName = DataSingleton.Instance.GetLinQContext().Tags
                             .Where(u => u.TagName.Contains(term)).Take(10)
                             .Select(u => new { label = u.TagName, id = u.TagsID });

            //var artTagName = DataSingleton.Instance.GetLinQContext().Tags
            //                 .Where(u => u.TagName.IndexOf(term) != -1).Take(10)
            //                 .Select(u => new { label = u.TagName, id = u.TagsID });

            if (artTagName.Count() == 0)
            {
                IEnumerable<Tag> tags = new Tag[] { new Tag { TagsID = 0, TagName = "Tag này chưa có" } };
                var aa = tags.Select(u => new { label = u.TagName, id = u.TagsID });
                return Json(aa.ToArray(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(artTagName.ToArray(), JsonRequestBehavior.AllowGet);
            }

            //return Json(artTagName.ToArray(), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// use in page ArticleEdit to autocomplete in field tags. Ajax
        /// </summary>
        /// <param name="term"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult GetTags2(string term, int articleID)
        {

            term = term.Trim();
          //term = term.Replace(" ", "");
            if (term.Length > 1)
            {
                int op = term.LastIndexOf(",");
                term = term.Substring(op + 1);
            }
            term = term.Trim();
            if (articleID == 0)//use in article create
            {
                var artTagName = DataSingleton.Instance.GetLinQContext().Tags
                                 .Where(u => u.TagName.Contains(term)).Take(20)
                                 .Select(u => new { label = u.TagName, id = u.TagsID });
                if (artTagName.Count() == 0)
                {
                    IEnumerable<Tag> tags = new Tag[] { new Tag { TagsID = 0, TagName = "Tag này chưa có" } };
                    var aa = tags.Select(u => new { label = u.TagName, id = u.TagsID });
                    return Json(aa.ToArray(), JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(artTagName.ToArray(), JsonRequestBehavior.AllowGet);
                }
            }
            else //use in article edit, get tags that the current article doesn't have.
            {
                IQueryable<int> existedTagIDs = DataSingleton.Instance.GetLinQContext().Article_Tags.Where(u => u.ArticleID == articleID)
                                                .Select(u=>u.TagsID);
                //IQueryable<Article_Tag> temp = DataSingleton.Instance.GetLinQContext().Article_Tags.Where(u => u.ArticleID == articleID);
                //List<int> existedTagIDs = new List<int>() { 0};
                //if (temp != null && temp.Count() > 0) 
                //{
                //    foreach (var item in temp)
                //    {
                //        existedTagIDs.Add(item.TagsID);
                //    }
                //}

                var artTagName = DataSingleton.Instance.GetLinQContext().Tags
                                 .Where(u => u.TagName.Contains(term) && !existedTagIDs.Contains(u.TagsID)).Take(20)
                                 .Select(u => new { label = u.TagName, id = u.TagsID });
                if (artTagName.Count() == 0)
                {
                    IEnumerable<Tag> tags = new Tag[] { new Tag { TagsID = 0, TagName = "Tag này chưa có hoặc có rồi" } };
                    var aa = tags.Select(u => new { label = u.TagName, id = u.TagsID });
                    return Json(aa.ToArray(), JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(artTagName.ToArray(), JsonRequestBehavior.AllowGet);
                }
            }
            
            //return Json(artTagName.ToArray(), JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// use in page ArticleEdit to create a tag quickly, ajax
        /// </summary>
        /// <param name="articleTypeID"></param>
        /// <param name="artid"></param>
        /// <returns></returns>
        [CheckMemberVisibility, Authorize(Roles = ConstantClass.articleAuthentication)]
        public ActionResult QuickCreateTag(string newTagName)
        {
            newTagName = newTagName.Trim();
            if (newTagName != null && newTagName.ToString() != "")
            {

                if (DataSingleton.Instance.GetTagsModels().InsertTag(newTagName, HttpContext.User.Identity.Name))
                {
                    return Content("Đã tạo tags \"" + newTagName + "\"");
                }
                else
                {
                    return Content("Thất bại, vui lòng thử lại.");
                }
            }
            else
            {
                return Content("Vui lòng nhập tag.");
            }
        }


        [CheckMemberVisibility, Authorize(Roles = ConstantClass.tagAuthentication)]
        public ActionResult TagsList_BackEnd(int tagID = 0, string amountOfTags = "500")
        {

            if (tagID <= 0)
            {
                ViewBag.TagDetails = new Tag();
            }
            else
            {
                ViewBag.TagDetails = DataSingleton.Instance.GetTagsModels().GetTagDetails(tagID);
            }

            ViewBag.amountList = new SelectList(new[] { "500", "1000", "2000", "3000", "5000" }.Select(x => new { value = x, text = x }), "value", "text", amountOfTags);
            ViewBag.AmountOfTags = amountOfTags;

            return View("/Views/BackEnd/Tags/TagsList.cshtml", DataSingleton.Instance.GetTagsModels().GetTagsListBackend(amountOfTags));
        }


        [CheckMemberVisibility, Authorize(Roles = ConstantClass.tagAuthentication), HttpPost, ValidateInput(false)]
        [ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult MakeTag(Tag tag)
        {
            if (tag.TagName != null)
            {
                string memberName = HttpContext.User.Identity.Name;
                //Edit tag
                if (tag.TagsID > 0)
                {
                    DataSingleton.Instance.GetTagsModels().EditTag(tag, memberName);
                }
                //Create tag
                else
                {
                    DataSingleton.Instance.GetTagsModels().CreateTag(tag, memberName);
                }
            }

            return RedirectToAction("TagsList_BackEnd", "Tags", new { tagID = tag.TagsID });
        }


        [CheckMemberVisibility, Authorize(Roles = ConstantClass.tagAuthentication), HttpPost, ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult DeleteTag(int tagID, string amountOfTags)
        {
            DataSingleton.Instance.GetTagsModels().DeleteTag(tagID);
            return RedirectToAction("TagsList_BackEnd", "Tags", new { amountOfTags = amountOfTags });
        }



        #endregion

    }
}
